/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.demister.at.model;

import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;

/**
 *
 * @author Rock
 */
public class GeneralBlockFrame extends BlockFrame {

    private Block[][] area;
    private Set<Block> set;

    public GeneralBlockFrame(int width, int height) {
        area = new Block[width][height];
        set = new TreeSet<Block>();
    }

    public int getWidth() {
        return area.length;
    }

    public int getHeight() {
        return area[0].length;
    }

    public Block get(int x, int y) {
        if (x < 0 || x >= this.getWidth() || y < 0 || y >= this.getHeight()) {
            return null;
        } else {
            return area[x][y];
        }
    }

    public Collection<Block> getAll() {
        return set;
    }

    public void add(Block b) {
        set.add(b);
        setArea(b);
    }

    public void remove(Block b) {
        set.remove(b);
        clearArea(b);
    }

    public void remove(int x, int y) {
        Block b = this.get(x, y);
        if (b != null) {
            remove(b);
        }
    }

    public void move(Block b, int x, int y) {
        clearArea(b);
        b.setX(x);
        b.setY(y);
        setArea(b);
    }

    public void move(int x, int y, int x1, int y1) {
        Block b = this.get(x, y);
        if (b == null) {
            return;
        }
        clearArea(b);
        b.setX(b.getX() + x1 - x);
        b.setY(b.getY() + y1 - y);
        setArea(b);
    }

    public void resize(Block b, int width, int height) {
        clearArea(b);
        b.setWidth(width);
        b.setHeight(height);
        setArea(b);
    }

    public void resize(int x, int y, int width, int height) {
        Block b = this.get(x, y);
        if (b == null) {
            return;
        }
        resize(b, width, height);
    }

    private void setArea(Block b) {
        for (int i = b.getX(); i < b.getBottomRightPoint().getX(); i++) {
            for (int j = b.getY(); j < b.getBottomRightPoint().getY(); j++) {
                area[i][j] = b;
            }
        }
    }

    private void clearArea(Block b) {
        for (int i = b.getX(); i < b.getBottomRightPoint().getX(); i++) {
            for (int j = b.getY(); j < b.getBottomRightPoint().getY(); j++) {
                area[i][j] = null;
            }
        }
    }

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < getHeight(); i++) {
            for (int j = 0; j < getWidth(); j++) {
                buffer.append(area[j][i] == null ? "   " : String.format("%2d ", area[j][i].getType()));
            }
            if (i != getHeight() - 1) {
                buffer.append("\n");
            }
        }
        return buffer.toString();
    }
}
